home *** CD-ROM | disk | FTP | other *** search
/ Skunkware 5 / Skunkware 5.iso / lib / perl5 / Getopt / Long.pm next >
Text File  |  1995-07-02  |  15KB  |  514 lines

  1. package Getopt::Long;
  2. require 5.000;
  3. require Exporter;
  4.  
  5. @ISA = qw(Exporter);
  6. @EXPORT = qw(GetOptions);
  7.  
  8.  
  9. # newgetopt.pl -- new options parsing
  10.  
  11. # SCCS Status     : @(#)@ newgetopt.pl    1.14
  12. # Author          : Johan Vromans
  13. # Created On      : Tue Sep 11 15:00:12 1990
  14. # Last Modified By: Johan Vromans
  15. # Last Modified On: Sat Feb 12 18:24:02 1994
  16. # Update Count    : 138
  17. # Status          : Okay
  18.  
  19. ################ Introduction ################
  20. #
  21. # This package implements an extended getopt function. This function adheres
  22. # to the new syntax (long option names, no bundling).
  23. # It tries to implement the better functionality of traditional, GNU and
  24. # POSIX getopt functions.
  25. # This program is Copyright 1990,1994 by Johan Vromans.
  26. # This program is free software; you can redistribute it and/or
  27. # modify it under the terms of the GNU General Public License
  28. # as published by the Free Software Foundation; either version 2
  29. # of the License, or (at your option) any later version.
  30. # This program is distributed in the hope that it will be useful,
  31. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  32. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  33. # GNU General Public License for more details.
  34. # If you do not have a copy of the GNU General Public License write to
  35. # the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, 
  36. # MA 02139, USA.
  37.  
  38. ################ Description ################
  39. #
  40. # Usage:
  41. #    require "newgetopt.pl";
  42. #    ...change configuration values, if needed...
  43. #    $result = &NGetOpt (...option-descriptions...);
  44. # Each description should designate a valid perl identifier, optionally
  45. # followed by an argument specifier.
  46. # Values for argument specifiers are:
  47. #   <none>   option does not take an argument
  48. #   !        option does not take an argument and may be negated
  49. #   =s :s    option takes a mandatory (=) or optional (:) string argument
  50. #   =i :i    option takes a mandatory (=) or optional (:) integer argument
  51. #   =f :f    option takes a mandatory (=) or optional (:) real number argument
  52. # If option "name" is set, it will cause the perl variable $opt_name to
  53. # be set to the specified value. The calling program can use this
  54. # variable to detect whether the option has been set. Options that do
  55. # not take an argument will be set to 1 (one).
  56. # Options that take an optional argument will be defined, but set to ''
  57. # if no actual argument has been supplied.
  58. # If an "@" sign is appended to the argument specifier, the option is
  59. # treated as an array. Value(s) are not set, but pushed into array
  60. # @opt_name.
  61. # Options that do not take a value may have an "!" argument spacifier to
  62. # indicate that they may be negated. E.g. "foo!" will allow -foo (which
  63. # sets $opt_foo to 1) and -nofoo (which will set $opt_foo to 0).
  64. # The option name may actually be a list of option names, separated by
  65. # '|'s, e.g. "foo|bar|blech=s". In this example, options 'bar' and
  66. # 'blech' will set $opt_foo instead.
  67. # Option names may be abbreviated to uniqueness, depending on
  68. # configuration variable $autoabbrev.
  69. # Dashes in option names are allowed (e.g. pcc-struct-return) and will
  70. # be translated to underscores in the corresponding perl variable (e.g.
  71. # $opt_pcc_struct_return).  Note that a lone dash "-" is considered an
  72. # option, corresponding perl identifier is $opt_ .
  73. # A double dash "--" signals end of the options list.
  74. # If the first option of the list consists of non-alphanumeric
  75. # characters only, it is interpreted as a generic option starter.
  76. # Everything starting with one of the characters from the starter will
  77. # be considered an option.
  78. # The default values for the option starters are "-" (traditional), "--"
  79. # (POSIX) and "+" (GNU, being phased out).
  80. # Options that start with "--" may have an argument appended, separated
  81. # with an "=", e.g. "--foo=bar".
  82. # If configuration varaible $getopt_compat is set to a non-zero value,
  83. # options that start with "+" may also include their arguments,
  84. # e.g. "+foo=bar".
  85. # A return status of 0 (false) indicates that the function detected
  86. # one or more errors.
  87. #
  88. ################ Some examples ################
  89. # If option "one:i" (i.e. takes an optional integer argument), then
  90. # the following situations are handled:
  91. #    -one -two        -> $opt_one = '', -two is next option
  92. #    -one -2        -> $opt_one = -2
  93. # Also, assume "foo=s" and "bar:s" :
  94. #    -bar -xxx        -> $opt_bar = '', '-xxx' is next option
  95. #    -foo -bar        -> $opt_foo = '-bar'
  96. #    -foo --        -> $opt_foo = '--'
  97. # In GNU or POSIX format, option names and values can be combined:
  98. #    +foo=blech        -> $opt_foo = 'blech'
  99. #    --bar=        -> $opt_bar = ''
  100. #    --bar=--        -> $opt_bar = '--'
  101. ################ Configuration values ################
  102. #   $autoabbrev      Allow option names to be abbreviated to uniqueness.
  103. #                    Default is 1 unless environment variable
  104. #                    POSIXLY_CORRECT has been set.
  105. #   $getopt_compat   Allow '+' to start options.
  106. #                    Default is 1 unless environment variable
  107. #                    POSIXLY_CORRECT has been set.
  108. #   $option_start    Regexp with option starters.
  109. #                    Default is (--|-) if environment variable
  110. #                    POSIXLY_CORRECT has been set, (--|-|\+) otherwise.
  111. #   $order           Whether non-options are allowed to be mixed with
  112. #                    options.
  113. #                    Default is $REQUIRE_ORDER if environment variable
  114. #                    POSIXLY_CORRECT has been set, $PERMUTE otherwise.
  115. #   $ignorecase      Ignore case when matching options. Default is 1.
  116. #   $debug           Enable debugging output. Default is 0.
  117.  
  118. ################ History ################
  119. # 12-Feb-1994        Johan Vromans    
  120. #    Added "!" for negation.
  121. #    Released to the net.
  122. #
  123. # 26-Aug-1992        Johan Vromans    
  124. #    More POSIX/GNU compliance.
  125. #    Lone dash and double-dash are now independent of the option prefix
  126. #      that is used.
  127. #    Make errors in NGetOpt parameters fatal.
  128. #    Allow options to be mixed with arguments.
  129. #      Check $ENV{"POSIXLY_CORRECT"} to suppress this.
  130. #    Allow --foo=bar and +foo=bar (but not -foo=bar).
  131. #    Allow options to be abbreviated to minimum needed for uniqueness.
  132. #      (Controlled by configuration variable $autoabbrev.)
  133. #    Allow alias names for options (e.g. "foo|bar=s").
  134. #    Allow "-" in option names (e.g. --pcc-struct-return). Dashes are
  135. #      translated to "_" to form valid perl identifiers
  136. #      (e.g. $opt_pcc_struct_return). 
  137. #
  138. # 2-Jun-1992        Johan Vromans    
  139. #    Do not use //o to allow multiple NGetOpt calls with different delimeters.
  140. #    Prevent typeless option from using previous $array state.
  141. #    Prevent empty option from being eaten as a (negative) number.
  142. #
  143. # 25-May-1992        Johan Vromans    
  144. #    Add array options. "foo=s@" will return an array @opt_foo that
  145. #    contains all values that were supplied. E.g. "-foo one -foo -two" will
  146. #    return @opt_foo = ("one", "-two");
  147. #    Correct bug in handling options that allow for a argument when followed
  148. #    by another option.
  149. #
  150. # 4-May-1992        Johan Vromans    
  151. #    Add $ignorecase to match options in either case.
  152. #    Allow '' option.
  153. #
  154. # 19-Mar-1992        Johan Vromans    
  155. #    Allow require from packages.
  156. #    NGetOpt is now defined in the package that requires it.
  157. #    @ARGV and $opt_... are taken from the package that calls it.
  158. #    Use standard (?) option prefixes: -, -- and +.
  159. #
  160. # 20-Sep-1990        Johan Vromans    
  161. #    Set options w/o argument to 1.
  162. #    Correct the dreadful semicolon/require bug.
  163.  
  164. ################ Configuration Section ################
  165.  
  166.  
  167.     # Values for $order. See GNU getopt.c for details.
  168.     $REQUIRE_ORDER = 0;
  169.     $PERMUTE = 1;
  170.     $RETURN_IN_ORDER = 2;
  171.  
  172.     # Handle POSIX compliancy.
  173.     if ( defined $ENV{"POSIXLY_CORRECT"} ) {
  174.     $autoabbrev = 0;    # no automatic abbrev of options (???)
  175.     $getopt_compat = 0;    # disallow '+' to start options
  176.     $option_start = "(--|-)";
  177.     $order = $REQUIRE_ORDER;
  178.     }
  179.     else {
  180.     $autoabbrev = 1;    # automatic abbrev of options
  181.     $getopt_compat = 1;    # allow '+' to start options
  182.     $option_start = "(--|-|\\+)";
  183.     $order = $PERMUTE;
  184.     }
  185.  
  186.     # Other configurable settings.
  187.     $debug = 0;            # for debugging
  188.     $ignorecase = 1;        # ignore case when matching options
  189.     $argv_end = "--";        # don't change this!
  190. }
  191.  
  192. ################ Subroutines ################
  193.  
  194. sub GetOptions {
  195.  
  196.     @optionlist = @_;    #';
  197.  
  198.     local ($[) = 0;
  199.     local ($genprefix) = $option_start;
  200.     local ($argend) = $argv_end;
  201.     local ($error) = 0;
  202.     local ($opt, $optx, $arg, $type, $mand, %opctl);
  203.     local ($pkg) = (caller)[0];
  204.     local ($optarg);
  205.     local (%aliases);
  206.     local (@ret) = ();
  207.  
  208.     print STDERR "NGetOpt 1.14 -- called from $pkg\n" if $debug;
  209.  
  210.     # See if the first element of the optionlist contains option
  211.     # starter characters.
  212.     if ( $optionlist[0] =~ /^\W+$/ ) {
  213.     $genprefix = shift (@optionlist);
  214.     # Turn into regexp.
  215.     $genprefix =~ s/(\W)/\\$1/g;
  216.     $genprefix = "[" . $genprefix . "]";
  217.     }
  218.  
  219.     # Verify correctness of optionlist.
  220.     %opctl = ();
  221.     foreach $opt ( @optionlist ) {
  222.     $opt =~ tr/A-Z/a-z/ if $ignorecase;
  223.     if ( $opt !~ /^(\w+[-\w|]*)?(!|[=:][infse]@?)?$/ ) {
  224.         die ("Error in option spec: \"", $opt, "\"\n");
  225.         $error++;
  226.         next;
  227.     }
  228.     local ($o, $c, $a) = ($1, $2);
  229.  
  230.     if ( ! defined $o ) {
  231.         $opctl{''} = defined $c ? $c : '';
  232.     }
  233.     else {
  234.         # Handle alias names
  235.         foreach ( split (/\|/, $o)) {
  236.         if ( defined $c && $c eq '!' ) {
  237.             $opctl{"no$_"} = $c;
  238.             $c = '';
  239.         }
  240.         $opctl{$_} = defined $c ? $c : '';
  241.         if ( defined $a ) {
  242.             # Note alias.
  243.             $aliases{$_} = $a;
  244.         }
  245.         else {
  246.             # Set primary name.
  247.             $a = $_;
  248.         }
  249.         }
  250.     }
  251.     }
  252.     @opctl = sort(keys (%opctl)) if $autoabbrev;
  253.  
  254.     return 0 if $error;
  255.  
  256.     if ( $debug ) {
  257.     local ($arrow, $k, $v);
  258.     $arrow = "=> ";
  259.     while ( ($k,$v) = each(%opctl) ) {
  260.         print STDERR ($arrow, "\$opctl{\"$k\"} = \"$v\"\n");
  261.         $arrow = "   ";
  262.     }
  263.     }
  264.  
  265.     # Process argument list
  266.  
  267.     while ( $#ARGV >= 0 ) {
  268.  
  269.     # >>> See also the continue block <<<
  270.  
  271.     #### Get next argument ####
  272.  
  273.     $opt = shift (@ARGV);
  274.     print STDERR ("=> option \"", $opt, "\"\n") if $debug;
  275.     $arg = undef;
  276.     $optarg = undef;
  277.     $array = 0;
  278.  
  279.     #### Determine what we have ####
  280.  
  281.     # Double dash is option list terminator.
  282.     if ( $opt eq $argend ) {
  283.         unshift (@ret, @ARGV) if $order == $PERMUTE;
  284.         return ($error == 0);
  285.     }
  286.     elsif ( $opt =~ /^$genprefix/ ) {
  287.         # Looks like an option.
  288.         $opt = $';        # option name (w/o prefix)
  289.         # If it is a long opt, it may include the value.
  290.         if (($+ eq "--" || ($getopt_compat && $+ eq "+")) && 
  291.         $opt =~ /^([^=]+)=/ ) {
  292.         $opt = $1;
  293.         $optarg = $';
  294.         print STDERR ("=> option \"", $opt, 
  295.                   "\", optarg = \"$optarg\"\n")
  296.             if $debug;
  297.         }
  298.  
  299.     }
  300.     # Not an option. Save it if we may permute...
  301.     elsif ( $order == $PERMUTE ) {
  302.         push (@ret, $opt);
  303.         next;
  304.     }
  305.     # ...otherwise, terminate.
  306.     else {
  307.         # Push back and exit.
  308.         unshift (@ARGV, $opt);
  309.         return ($error == 0);
  310.     }
  311.  
  312.     #### Look it up ###
  313.  
  314.     $opt =~ tr/A-Z/a-z/ if $ignorecase;
  315.  
  316.     local ($tryopt) = $opt;
  317.     if ( $autoabbrev ) {
  318.         local ($pat, @hits);
  319.  
  320.         # Turn option name into pattern.
  321.         ($pat = $opt) =~ s/(\W)/\\$1/g;
  322.         # Look up in option names.
  323.         @hits = grep (/^$pat/, @opctl);
  324.         print STDERR ("=> ", 0+@hits, " hits (@hits) with \"$pat\" ",
  325.               "out of ", 0+@opctl, "\n")
  326.         if $debug;
  327.  
  328.         # Check for ambiguous results.
  329.         unless ( (@hits <= 1) || (grep ($_ eq $opt, @hits) == 1) ) {
  330.         print STDERR ("Option ", $opt, " is ambiguous (",
  331.                   join(", ", @hits), ")\n");
  332.         $error++;
  333.         next;
  334.         }
  335.  
  336.         # Complete the option name, if appropriate.
  337.         if ( @hits == 1 && $hits[0] ne $opt ) {
  338.         $tryopt = $hits[0];
  339.         print STDERR ("=> option \"$opt\" -> \"$tryopt\"\n")
  340.             if $debug;
  341.         }
  342.     }
  343.  
  344.     unless  ( defined ( $type = $opctl{$tryopt} ) ) {
  345.         print STDERR ("Unknown option: ", $opt, "\n");
  346.         $error++;
  347.         next;
  348.     }
  349.     $opt = $tryopt;
  350.     print STDERR ("=> found \"$type\" for ", $opt, "\n") if $debug;
  351.  
  352.     #### Determine argument status ####
  353.  
  354.     # If it is an option w/o argument, we're almost finished with it.
  355.     if ( $type eq '' || $type eq '!' ) {
  356.         if ( defined $optarg ) {
  357.         print STDERR ("Option ", $opt, " does not take an argument\n");
  358.         $error++;
  359.         }
  360.         elsif ( $type eq '' ) {
  361.         $arg = 1;        # supply explicit value
  362.         }
  363.         else {
  364.         substr ($opt, 0, 2) = ''; # strip NO prefix
  365.         $arg = 0;        # supply explicit value
  366.         }
  367.         next;
  368.     }
  369.  
  370.     # Get mandatory status and type info.
  371.     ($mand, $type, $array) = $type =~ /^(.)(.)(@?)$/;
  372.  
  373.     # Check if there is an option argument available.
  374.     if ( defined $optarg ? ($optarg eq '') : ($#ARGV < 0) ) {
  375.  
  376.         # Complain if this option needs an argument.
  377.         if ( $mand eq "=" ) {
  378.         print STDERR ("Option ", $opt, " requires an argument\n");
  379.         $error++;
  380.         }
  381.         if ( $mand eq ":" ) {
  382.         $arg = $type eq "s" ? '' : 0;
  383.         }
  384.         next;
  385.     }
  386.  
  387.     # Get (possibly optional) argument.
  388.     $arg = defined $optarg ? $optarg : shift (@ARGV);
  389.  
  390.     #### Check if the argument is valid for this option ####
  391.  
  392.     if ( $type eq "s" ) {    # string
  393.         # A mandatory string takes anything. 
  394.         next if $mand eq "=";
  395.  
  396.         # An optional string takes almost anything. 
  397.         next if defined $optarg;
  398.         next if $arg eq "-";
  399.  
  400.         # Check for option or option list terminator.
  401.         if ($arg eq $argend ||
  402.         $arg =~ /^$genprefix.+/) {
  403.         # Push back.
  404.         unshift (@ARGV, $arg);
  405.         # Supply empty value.
  406.         $arg = '';
  407.         }
  408.         next;
  409.     }
  410.  
  411.     if ( $type eq "n" || $type eq "i" ) { # numeric/integer
  412.         if ( $arg !~ /^-?[0-9]+$/ ) {
  413.         if ( defined $optarg || $mand eq "=" ) {
  414.             print STDERR ("Value \"", $arg, "\" invalid for option ",
  415.                   $opt, " (number expected)\n");
  416.             $error++;
  417.             undef $arg;    # don't assign it
  418.         }
  419.         else {
  420.             # Push back.
  421.             unshift (@ARGV, $arg);
  422.             # Supply default value.
  423.             $arg = 0;
  424.         }
  425.         }
  426.         next;
  427.     }
  428.  
  429.     if ( $type eq "f" ) { # fixed real number, int is also ok
  430.         if ( $arg !~ /^-?[0-9.]+$/ ) {
  431.         if ( defined $optarg || $mand eq "=" ) {
  432.             print STDERR ("Value \"", $arg, "\" invalid for option ",
  433.                   $opt, " (real number expected)\n");
  434.             $error++;
  435.             undef $arg;    # don't assign it
  436.         }
  437.         else {
  438.             # Push back.
  439.             unshift (@ARGV, $arg);
  440.             # Supply default value.
  441.             $arg = 0.0;
  442.         }
  443.         }
  444.         next;
  445.     }
  446.  
  447.     die ("NGetOpt internal error (Can't happen)\n");
  448.     }
  449.  
  450.     continue {
  451.     if ( defined $arg ) {
  452.         $opt = $aliases{$opt} if defined $aliases{$opt};
  453.         # Make sure a valid perl identifier results.
  454.         $opt =~ s/\W/_/g;
  455.         if ( $array ) {
  456.         print STDERR ('=> push (@', $pkg, '\'opt_', $opt, ", \"$arg\")\n")
  457.             if $debug;
  458.             eval ('push(@' . $pkg . '\'opt_' . $opt . ", \$arg);");
  459.         }
  460.         else {
  461.         print STDERR ('=> $', $pkg, '\'opt_', $opt, " = \"$arg\"\n")
  462.             if $debug;
  463.             eval ('$' . $pkg . '\'opt_' . $opt . " = \$arg;");
  464.         }
  465.     }
  466.     }
  467.  
  468.     if ( $order == $PERMUTE && @ret > 0 ) {
  469.     unshift (@ARGV, @ret);
  470.     }
  471.     return ($error == 0);
  472. }
  473.  
  474. ################ Package return ################
  475.  
  476. 1;
  477.  
  478.  
  479.